<template>
  <div style=" width: 100%; height: 100%; position: relative">
    <div :id="mapId" class="map"></div>
    <loading-mask
        style="z-index: -5"
        :loading="maskLoading"
    ></loading-mask>
  </div>
</template>
<script>

import LoadingMask from "./animation/LoadingMask.vue";
import getters from '../store/getters';
export default {
  name: "EpgisMap",
  components: {LoadingMask},
  props: {
    mapParams: {
      type: Object,
      default() {
        return {}
      }
    },
    isOuterLoading: {
      type: Boolean,
      default() {
        return false;
      }
    }
  },
  created() {
    this.mapId = 'map-' + this.generateRandom6DigitNumber();
  },
  mounted() {
      this.initEpgis((epgis,sgKey,sgSecret) =>{
        this.epgis=epgis;
        this.epgis.tokenTask.login(
            sgKey,
            sgSecret
        ).then(() =>{
          this.register(sgKey,sgSecret);
        })
      })
  },
  data() {
    return {
      epgis: this.$store.getters.epgis,
      mapId: null,
      map: null,
      elMarker: null,
      loading: true,
      roadNetLayer: null,
    }
  },
  methods: {
    generateRandom6DigitNumber() {
      // 生成一个 0 到 999999 之间的随机数
      const randomNumber = Math.floor(Math.random() * 1000000);
      // 补全 6 位，如果不足 6 位则在前面补 0
      return String(randomNumber).padStart(6, '0');
    },
    initEpgis(callback) {
      fetch('/api/getSJConfig') // 假设后端接口是 /api/config
          .then(response => response.json()) // 将响应数据解析为 JSON
          .then(data => {
            let linkSGScript = document.createElement("link");
            let secSGScript = document.createElement("script");
            let href = data.sgApi + '/api/epgis-1.5.0.css';
            let src = data.sgApi + '/api/epgis-js-1.5.0.min.js';
            linkSGScript.setAttribute("rel", "stylesheet")
            linkSGScript.setAttribute("href", href)
            document.head.insertBefore(linkSGScript, document.head.lastChild);
            secSGScript.setAttribute("src", src)
            document.head.insertBefore(secSGScript, document.head.lastChild);
            secSGScript.onload = secSGScript.onreadystatechange = function () {
              if (!this.readyState || this.readyState === "loaded" || this.readyState === "complete") {
                secSGScript.onload = secSGScript.onreadystatechange = null;
                if (callback && typeof callback == "function") {
                  if (typeof epgis != 'undefined') {
                    callback(epgis, data.sgKey, data.sgSecret)
                  }
                }
              }
            }
          })
    },
    register(sgKey,sgSecret) {

      let register;
      if (!getters.isMapLogin) {
        console.log('register!');
        register = this.$store.dispatch("map/login", {
          key: sgKey,
          secret: sgSecret
        });
      } else register = new Promise((resolve, reject) => resolve());
      register.then(() => {
        this.doCreate();
      });
    },
    doCreate() {
      this.initMap();
    },
    initMap() {
      this.showLoading();
      this.map = new this.epgis.Map({
        container: this.mapId,
        style: this.mapParams.mapStyle || "aegis://styles/aegis/Satellite512",
        zoom: this.mapParams.zoom || 15,
        bearing: this.mapParams.bearing || 0,
        // maxZoom: this.mapParams.maxZoom || 24,
        // minZoom: this.mapParams.minZoom || 6,
        trackResize: true,
        doubleClickZoom: false,
        center: this.mapParams.center || [112.63546014576417, 35.03502734505277],
        localIdeographFontFamily: "'PingFang SC', 'Microsoft YoHei'",
      });

      this.map.on("load", () => {
        // this.roadNetLayer = new SGMap.RoadNetLayer({map: this.map, style: "aegis://styles/aegis/Road-v2"});
        // this.roadNetLayer && this.roadNetLayer.render();
        this.hideLoading();
        this.$emit('map-inited', this.map);
      });

    },
    flyTo() {
      // this.map.flyTo({
      //     center: res.center,
      //     zoom: res.zoom || 13,
      //     speed: res.speed || 2
      // });

    },
    showLoading() {
      this.loading = true;
    },
    hideLoading() {
      this.loading = false;
    }
  },
  computed: {
    maskLoading() {
      return this.isOuterLoading ? false : this.loading;
    }
  },
  beforeDestroy() {
    this.roadNetLayer && this.roadNetLayer.destroy();
  }
}

</script>
<style scoped>

.map {
  width: 100%;
  height: 100%;
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s ease;
}

.fade-enter,
.fade-leave-to {
  opacity: 0;
}
</style>
